package com.tim.app.ui.adapter.message;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.log.DLOG;
import com.application.library.util.TimeUtil;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.roundimg.RoundedImageView;
import com.netease.nim.session.extension.GuessAttachment;
import com.netease.nim.session.extension.SnapChatAttachment;
import com.netease.nim.session.extension.StickerAttachment;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.session.helper.TeamNotificationHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.attachment.NotificationAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.uinfo.UserInfoProvider;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.tim.app.R;
import com.tim.app.netease.cache.NimUserInfoCache;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.TextUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 最近联系
 */
public class RecentContactAdapter extends BaseRecyclerAdapter<BaseRecyclerAdapter.BaseRecyclerViewHolder, RecentContact> {

    private Context mContext;

    public RecentContactAdapter(Context mContext, List<RecentContact> mDataList) {
        super(mDataList);
        this.mContext = mContext;
    }

    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseRecyclerViewHolder holder = null;
        holder = new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_recent_contact, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder mHolder, final int position, final RecentContact data) {
        if (data == null) {
            return;
        }
        final ViewHolder holder = (ViewHolder) mHolder;
        holder.tvLastMessageTime.setText(TimeUtil.formatTimeRuleOne(mContext, data.getTime()));
        final UserInfoProvider.UserInfo userInfo = NimUserInfoCache.getInstance().getUserInfo(data.getContactId());
        if (null != userInfo) {
            if (!TextUtils.isEmpty(userInfo.getName())) {
                holder.tvUserName.setText(userInfo.getName());
            } else {
                holder.tvUserName.setText("");
            }
            if (!TextUtils.isEmpty(userInfo.getAvatar())) {
                BitmapLoader.ins().loadImage(userInfo.getAvatar(), holder.rivAvatar);
            } else {
                BitmapLoader.ins().loadImage("", holder.rivAvatar);
            }
            Map<String, Object> extension = new HashMap<String, Object>();
            extension.put("name", userInfo.getName());
            extension.put("avatar", userInfo.getAvatar());
            data.setExtension(extension);
            getDataList().set(position, data);
        } else {
            if (data.getExtension() != null) {
                Map<String, Object> extension = data.getExtension();
                if (extension.containsKey("name")) {
                    String name = extension.get("name").toString();
                    if (!TextUtils.isEmpty(name)) {
                        holder.tvUserName.setText(name);
                    }
                }

                if (extension.containsKey("avatar")) {
                    String avatar = extension.get("avatar").toString();
                    if (!TextUtils.isEmpty(avatar)) {
                        BitmapLoader.ins().loadImage(avatar, holder.rivAvatar);
                    }
                }
            } else {
                List<String> accounts = new ArrayList<>(1);
                accounts.add(UserManager.ins().getChatId(data.getContactId()));

                NIMClient.getService(UserService.class).fetchUserInfo(accounts)
                        .setCallback(new RequestCallback<List<NimUserInfo>>() {
                            @Override
                            public void onSuccess(List<NimUserInfo> users) {
                                if (null != users && users.size() > 0) {
                                    NimUserInfo user = users.get(0);
                                    if (!TextUtils.isEmpty(user.getAvatar())) {
                                        BitmapLoader.ins().loadImage(user.getAvatar(), holder.rivAvatar);
                                    }
                                    if (!TextUtils.isEmpty(user.getName())) {
                                        holder.tvUserName.setText(user.getName());
                                    }
                                    Map<String, Object> extension = new HashMap<String, Object>();
                                    extension.put("name", user.getName());
                                    extension.put("avatar", user.getAvatar());
                                    data.setExtension(extension);
                                    getDataList().set(position, data);
                                }
                            }

                            @Override
                            public void onFailed(int code) {

                            }

                            @Override
                            public void onException(Throwable exception) {

                            }
                        });
            }
        }
        if (!TextUtils.isEmpty(data.getContent())) {
            holder.tvLastMessageDesc.setVisibility(View.VISIBLE);
            holder.tvLastMessageDesc.setText(descOfMsg(data));
        } else {
            holder.tvLastMessageDesc.setVisibility(View.GONE);
        }
        if (data.getUnreadCount() == 0) {
            holder.tvUnReadMessageCount.setVisibility(View.GONE);
        } else {
            holder.tvUnReadMessageCount.setVisibility(View.VISIBLE);
            if (data.getUnreadCount() > 99) {
                holder.tvUnReadMessageCount.setText("···");
            } else {
                holder.tvUnReadMessageCount.setText(String.valueOf(data.getUnreadCount()));
            }
        }
        holder.llRight.setVisibility(View.VISIBLE);

        holder.rivAvatar.setTag(data);
        holder.tvUserName.setTag(data);
        holder.tvUserName.setOnClickListener(onClickListener);
        holder.rivAvatar.setOnClickListener(onClickListener);
        if (position == getDataList().size() - 1) {
            holder.vLine.setVisibility(View.GONE);
        } else {
            holder.vLine.setVisibility(View.VISIBLE);
        }
    }

    protected String descOfMsg(RecentContact recent) {
        if (recent.getMsgType() == MsgTypeEnum.text) {
            return recent.getContent();
        } else if (recent.getMsgType() == MsgTypeEnum.tip) {
            String digest = null;
            if (digest == null) {
                digest = getDefaultDigest(null, recent);
            }
            return digest;
        } else if (recent.getAttachment() != null) {
            String digest = null;
            if (recent.getAttachment() instanceof GuessAttachment) {
                GuessAttachment guess = (GuessAttachment) recent.getAttachment();
                return "[猜拳] " + guess.getValue().getDesc();
            } else if (recent.getAttachment() instanceof StickerAttachment) {
                return "[贴图]";
            } else if (recent.getAttachment() instanceof SnapChatAttachment) {
                return "[阅后即焚]";
            }

            if (digest == null) {
                digest = getDefaultDigest(recent.getAttachment(), recent);
            }

            return digest;
        }
        return "";
    }


    // SDK本身只记录原始数据，第三方APP可根据自己实际需求，在最近联系人列表上显示缩略消息
    // 以下为一些常见消息类型的示例。
    private String getDefaultDigest(MsgAttachment attachment, RecentContact recent) {
        switch (recent.getMsgType()) {
            case text:
                return recent.getContent();
            case image:
                return "[图片]";
            case video:
                return "[视频]";
            case audio:
                return "[语音消息]";
            case location:
                return "[位置]";
            case file:
                return "[文件]";
            case tip:
                List<String> uuids = new ArrayList<>();
                uuids.add(recent.getRecentMessageId());
                List<IMMessage> messages = NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuids);
                if (messages != null && messages.size() > 0) {
                    return messages.get(0).getContent();
                }
                return "[通知提醒]";
            case notification:
                return TeamNotificationHelper.getTeamNotificationText(recent.getContactId(),
                        recent.getFromAccount(),
                        (NotificationAttachment) recent.getAttachment());
            default:
                return "[自定义消息] ";
        }
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecentContact data = (RecentContact) v.getTag();
            User user = new User();
            user.setUserId(data.getContactId().replace("moli", ""));
            SomeoneHomepageActivity.start(mContext, user, false);
        }
    };

    public class ViewHolder extends BaseRecyclerViewHolder {

        RoundedImageView rivAvatar;
        TextView tvLastMessageTime, tvUnReadMessageCount;
        TextView tvUserName, tvLastMessageDesc;
        RelativeLayout llRight;
        View vLine;

        public ViewHolder(View itemView) {
            super(itemView);
            rivAvatar = (RoundedImageView) itemView.findViewById(R.id.rivAvatar);
            tvLastMessageTime = (TextView) itemView.findViewById(R.id.tvLastMessageTime);
            tvUnReadMessageCount = (TextView) itemView.findViewById(R.id.tvUnReadMessageCount);
            llRight = (RelativeLayout) itemView.findViewById(R.id.llRight);
            tvUserName = (TextView) itemView.findViewById(R.id.tvUserName);
            tvLastMessageDesc = (TextView) itemView.findViewById(R.id.tvLastMessageDesc);
            vLine = itemView.findViewById(R.id.vLine);
        }

    }

}
